package com.wlz.leaderSelector;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 *  leader 选举 demo 实现
 * @author wlz
 * @date 2022-06-26  6:05 下午
 */
@Slf4j
public class LeaderSelectorDemo {

    private static final String ZK_ADDRESS = "106.52.11.147:2181";

    private static RetryPolicy retryPolicy=new ExponentialBackoffRetry( 5*1000, 10 );

    private  static  CuratorFramework curatorFramework;

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) throws Exception{

        String appName = System.getProperty("appName");

        curatorFramework = CuratorFrameworkFactory.newClient(ZK_ADDRESS, retryPolicy);
        curatorFramework.start();

        LeaderSelectorListener listener = new LeaderSelectorListener() {
            @Override
            public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
                log.info("stateChanged , {}", connectionState.isConnected());
            }
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                log.info("I`m leader now . I`m , {}", appName);
                TimeUnit.SECONDS.sleep(5);
            }
        };

        LeaderSelector selector = new LeaderSelector(curatorFramework, "/cachePreHeat_leader", listener);
        selector.autoRequeue();
        selector.start();
        countDownLatch.await();
    }

}
